﻿using System.Diagnostics;
using Core;

namespace RevisionItNow
{
	public class Mercurial
	{
	    private static OutputPane _outputPane;

	    public static OutputPane OutputPane
	    {
            set { _outputPane = value; }
	    }

		public static string HgPath
		{
			get { return "C:\\Program Files\\Mercurial\\hg.exe"; }
		}

		public static void Add(string path)
		{
			RunMercurialCommand("add " + MercurialFriendlyPath(path));
		}

        public static void Delete(string path)
		{
			RunMercurialCommand("remove " + MercurialFriendlyPath(path));
		}

        public static void Revert(string path)
		{
			RunMercurialCommand("revert " + MercurialFriendlyPath(path));
		}

        public static void Rename(string from, string to)
		{
			RunMercurialCommand("rename " + MercurialFriendlyPath(from) + " " + MercurialFriendlyPath(to));
		}

		public static void Version()
		{
			RunMercurialCommand("version");
		}

        public static void History(string path)
        {
            RunMercurialCommand("log " + MercurialFriendlyPath(path));
        }

	    private static void RunMercurialCommand(string arguments)
		{
            if (_outputPane != null)
                _outputPane.PrintMessage(HgPath + " " + arguments);

            var info = new ProcessStartInfo(HgPath)
            {
                Arguments = arguments,
                CreateNoWindow = true,
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardError = true
            };

            Process process = Process.Start(info);
            process.WaitForExit();

            if (_outputPane != null)
                _outputPane.PrintMessage(process.StandardOutput.ReadToEnd());
		}

		private static string MercurialFriendlyPath(string input)
		{
			return input.Replace("#", "%23");
		}
	}
}